package activity

import (
	"fmt"
	"gq_volunteer_platform/bean"
	"gq_volunteer_platform/model/activity"

	"github.com/gin-gonic/gin"
)

func AllTypeList(c *gin.Context) {

	var list []struct {
		ID   uint
		Name string
	}

	var tx = bean.MysqlDb.Model(&activity.ActivityType{})

	// 查询列表
	if err := tx.Order("`sort` ASC").Find(&list).Error; err != nil {
		bean.Log.Error(err)
		c.String(500, err.Error())
		return
	}

	c.PureJSON(200, gin.H{
		"list": list,
	})
}

func TypeList(c *gin.Context) {

	var req struct {
		Page  int    `binding:"required,gte=1"`
		Limit int    `binding:"required,gte=1"`
		Name  string `binding:"max=255"`
	}

	if err := c.ShouldBindQuery(&req); err != nil {
		bean.Log.Warning(err.Error())
		c.String(400, err.Error())
		return
	}

	var offset = (req.Page - 1) * req.Limit

	var count int64

	var list []struct {
		ID   uint
		Name string
		Sort uint
	}

	var tx = bean.MysqlDb.Model(&activity.ActivityType{})

	if req.Name != "" {
		tx = tx.Where("`name` like ?", "%"+req.Name+"%")
	}

	// 查询总数
	if err := tx.Count(&count).Error; err != nil {
		bean.Log.Error(err)
		c.String(500, err.Error())
		return
	}

	// 查询列表
	if err := tx.Limit(req.Limit).Offset(offset).Order("`sort` ASC").Find(&list).Error; err != nil {
		bean.Log.Error(err)
		c.String(500, err.Error())
		return
	}

	c.PureJSON(200, gin.H{
		"list":  list,
		"count": count,
	})
}

func TypeEdit(c *gin.Context) {

	var req struct {
		ID   uint   `binding:"max=10000000"`
		Name string `binding:"max=255"`
		Sort uint   `binding:"max=10000"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		bean.Log.Warning(err)
		c.String(400, err.Error())
		return
	}

	var one activity.ActivityType

	one.ID = req.ID
	one.Name = req.Name
	one.Sort = req.Sort

	// 保存对象
	if one.ID == 0 {
		if err := bean.MysqlDb.Create(&one).Error; err != nil {
			bean.Log.Error(err)
			c.String(500, "数据库错误")
			return
		}
	} else {
		if err := bean.MysqlDb.Updates(&one).Error; err != nil {
			bean.Log.Error(err)
			c.String(500, "数据库错误")
			return
		}
	}

	c.String(200, "ok")
}

func TypeDelete(c *gin.Context) {

	var req struct {
		ID uint `binding:"max=10000000"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		bean.Log.Warning(err)
		c.String(400, err.Error())
		return
	}

	var one activity.ActivityType
	if err := bean.MysqlDb.Where("id=?", req.ID).First(&one).Error; err != nil {
		bean.Log.Warning(err)
		c.String(400, fmt.Sprintf("类型不存在id:%d", req.ID))
		return
	}

	if err := bean.MysqlDb.Delete(&one).Error; err != nil {
		bean.Log.Error(err)
		c.String(500, err.Error())
		return
	}

	c.String(200, "ok")
}
